<template>
  <div class="modal">
    <el-dialog
      v-model="dialogVisible"
      :title="
        isNewRef ? modalConfig.header?.newTitle : modalConfig.header?.editTitle
      "
      :width="modalConfig.header?.width ?? '30%'"
      center
    >
      <el-watermark
        :font="font"
        :content="['石家庄巨创科技有限公司']"
        :offset="[100, 20]"
        :gap="[200, 280]"
      >
        <div class="form">
          <el-form
            :model="formData"
            label-width="80px"
            size="large"
            ref="formRef"
          >
            <template v-for="item in modalConfig.propItems" :key="item.prop">
              <template v-if="item.type === 'input'">
                <el-form-item
                  :label="item.label"
                  :prop="item.prop"
                  :rules="item.rules"
                >
                  <el-input
                    v-model="formData[item.prop!]"
                    :placeholder="item.placeholder"
                    :disabled="isNewRef ? false : item.disabled"
                  />
                </el-form-item>
              </template>
              <template v-else-if="item.type === 'date-picker'">
                <el-form-item>
                  <el-date-picker
                    v-model="formData[item.prop!]"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                </el-form-item>
              </template>
              <template v-else-if="item.type === 'select'">
                <el-form-item :label="item.label" :prop="item.prop">
                  <el-select
                    v-model="formData[item.prop!]"
                    :placeholder="item.placeholder"
                    style="width: 100%"
                  >
                    <template
                      v-for="option in item.options"
                      :key="option.value"
                    >
                      <el-option :label="option.label" :value="option.value" />
                    </template>
                  </el-select>
                </el-form-item>
              </template>
              <template v-else-if="item.type === 'radio'">
                <el-form-item :label="item.label" :prop="item.prop">
                  <el-radio-group v-model="formData[item.prop!]">
                    <template
                      v-for="option in item.options"
                      :key="option.value"
                    >
                      <el-radio
                        :label="option.label"
                        :value="option.value"
                      ></el-radio>
                    </template>
                  </el-radio-group>
                </el-form-item>
              </template>
              <template v-else-if="item.type === 'custom'">
                <el-form-item :label="item.label" :prop="item.prop">
                  <slot :name="item.slotName"></slot>
                </el-form-item>
              </template>
            </template>
          </el-form>
        </div>
      </el-watermark>
      <template #footer>
        <span class="dialog-footer">
          <el-button :icon="Close" @click="handleCancleClick(formRef)">
            取消
          </el-button>
          <el-button
            :icon="Select"
            type="primary"
            @click="handleComfirmClick(formRef)"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 模块引入
import { ref, reactive, toRaw } from 'vue'
import { ElNotification, ElForm } from 'element-plus'
import { Close, Select } from '@element-plus/icons-vue'
// import type {FormRules} from 'element-plus'
import type { IModalProps } from '@/components/types'
import useSystemStore from '@/store/main/system/system'

defineOptions({
  // 组件名称
  name: 'ModalComp',
  // 继承透传，是否继承没在子组件声明的父组件的属性
  inheritAttrs: true
})

// 1、接收父组件传递的参数
const props = defineProps<IModalProps>()

// 2、定义dialog显示状态
const dialogVisible = ref<boolean>(false)

// 2.1、获取当前分类的名称
const { category, pageName } = props.modalConfig
const apiPageName = `${category}/${pageName}`

// const rules=reactive<FormRules<formData> >({})
// 3、初始化表单
const initialForm: any = {}
for (const item of props.modalConfig.propItems) {
  if (item.prop) {
    initialForm[item.prop] = ''
  }
}
const formData = reactive(initialForm)
const font = reactive({
  color: 'rgba(0, 0, 0, 0.1)'
})
// 4、定义新增或编辑状态
const isNewRef = ref(false)
const editData = ref(null)

// 5、控制模态框显示与否
function setModalVisible(isNew = true, itemData?: any) {
  dialogVisible.value = true
  isNewRef.value = isNew
  // console.log(itemData)

  if (!isNew && itemData) {
    // console.log(itemData)

    for (const key in formData) {
      formData[key] = itemData[key]
    }
    editData.value = itemData
  } else {
    for (const key in formData) {
      // const item = props.modalConfig.formItems.find((item) => item.prop === key)
      formData[key] = ''
    }
    editData.value = null
  }
}

// 6、确认按钮点击事件
const systemStore = useSystemStore()
function handleComfirmClick(form: any) {
  if (!form) return
  form.validate(async (valid: boolean) => {
    // console.log(valid)

    if (valid) {
      let infoData = { ...formData }
      if (props.otherInfo) {
        const otherInfo = toRaw(props.otherInfo)
        infoData = { ...infoData, ...otherInfo }
      }
      // console.log(infoData)
      if (!isNewRef.value && editData.value) {
        const id = editData.value['_id']
        await systemStore.updatePageAction(apiPageName, id, infoData)
        ElNotification.success({
          title: '成功提示',
          message: `${props.modalConfig.header?.editTitle}信息成功！`
        })
      } else {
        // 新增部门数据
        // console.log(infoData)
        await systemStore.createPageAction(apiPageName, infoData)
        ElNotification.success({
          title: '成功提示',
          message: `${props.modalConfig.header?.newTitle}信息成功！`
        })
      }
      dialogVisible.value = false
    } else {
      ElNotification.error({
        title: '错误提示',
        message: '请输入完整信息！'
      })
    }
  })
}

const formRef = ref<InstanceType<typeof ElForm>>()
const handleCancleClick = (form: any) => {
  if (!form) return
  // form中的数据全部重置
  // 想要通过resetFields()进行重置，必须要绑定prop在每个el-form-item上
  form.resetFields()
  if (isNewRef.value) {
    ElNotification.info({
      title: '取消提示',
      message: `取消${props.modalConfig.header?.newTitle}成功！`
    })
  } else {
    ElNotification.info({
      title: '取消提示',
      message: `取消${props.modalConfig.header?.editTitle}成功！`
    })
  }
  dialogVisible.value = false
}

defineExpose({
  setModalVisible
})
</script>

<style scoped lang="scss">
.form {
  padding: 0 20px;
}
</style>
